'libtgfx - Threaded Graphics library for FreeBASIC
'Copyright (C) 2013  Ebben Feagan <sir@mud.owlbox.net>
'
'This library is free software; you can redistribute it and/or
'modify it under the terms of the GNU Lesser General Public
'License as published by the Free Software Foundation; either
'version 2.1 of the License, or (at your option) any later version.
'
'This library is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
'Lesser General Public License for more details.
'
'You should have received a copy of the GNU Lesser General Public
'License along with this library; if not, write to the Free Software
'Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include once "tgfx.bi"
#include once "tgfx-priv.bi"

dim shared wt_id as any ptr

sub cleanup cdecl export
    if Comm <> 0 then
        Comm->send(new Message(tgfx._MEXIT))
        threadwait wt_id
        delete Comm
    end if
end sub


    namespace tgfx.window

        sub clear() export
            Comm->send(new Message(_MCLS))
        end sub

        function init(  byval x as integer, _
                            byval y as integer, _
                            byval bpp as GFXmode = _32bit, _
                            byval flags as integer = 0 _
                        ) as bool export

            if Comm <> 0 then return false

            Comm = new CommChannel()
            std.atexit(@cleanup)
            wt_id = threadcreate (@GfxHandler, 0)

            var cc = new CommChannel()
            Comm->send(new Message(_MINIT,new Mdata(new init_data(Coord(x,y),bpp,flags),@init_d_free),cc))
            var ret = cc->recv()
            while ret = 0: ret = cc->recv() : wend
            if ret->c = _MTRUE then
                delete ret
                delete cc
                return true
            else
                delete ret
                delete cc
                return false
            end if
        end function

        sub setTitle( byref rhs as const string ) export
            Comm->send(new Message(_MTITLE,new Mdata(new str_data(rhs),@str_d_free)))
        end sub

        function screendata( ) as any ptr export
            var cc = new CommChannel()
            Comm->send(new Message(_MSPTR,,cc))
            var ret = cc->recv()
            while ret = 0 : ret = cc->recv() : wend
            var ret_p = ret->x
            ret->x = 0
            delete ret
            delete cc
            return ret_p
        end function

        sub lock() export
            Comm->send(new Message(_MLOCK))
        end sub

        sub unlock() export
            Comm->send(new Message(_MULOCK))
        end sub

    end namespace
